import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:gksz/political_Theory/Recommend/MessagePage/MessagePage.dart';
import 'package:gksz/political_Theory/Video/VideoPage.dart';
import 'dart:ui';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:dio/dio.dart';

Dio dio = new Dio();

class Recommend extends StatefulWidget {
  Recommend({Key key}) : super(key: key);
  _RecommendState createState() => _RecommendState();
}

class _RecommendState extends State<Recommend> {
  buildSwiperPagination() {
    return SwiperPagination(
      alignment: Alignment.bottomRight,
      margin: const EdgeInsets.fromLTRB(0, 0, 15, 5),
      builder: FractionPaginationBuilder(
          activeFontSize: 18,
          fontSize: 15,
          color: Colors.red,
          activeColor: Colors.white),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return Stack(
      children: <Widget>[
        Image.network(
          "${_res[index]['album']}",
          fit: BoxFit.cover,
          height: 200.0,
          width: MediaQuery.of(context).size.width,
        ),
        Positioned(
          bottom: 0,
          child: Container(
            color: Color.fromRGBO(0, 0, 0, 0.7),
            height: 60.0,
            width: MediaQuery.of(context).size.width,
            child: Text(
              "${_res[index]['title']}",
              style: TextStyle(
                  fontSize: 18.0,
                  fontWeight: FontWeight.w600,
                  color: Colors.white),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
          ),
        )
      ],
    );
  }

  List<String> items = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
  ];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1500));
    _refreshController.refreshCompleted();
    message();
  }

  void _onLoading() async {
    await Future.delayed(Duration(seconds: 1));

    if (items.length < _res.length-5) {
      items.add((items.length + 1).toString());
    }

    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return _res == null
        ? Center(
          child:Container(
          width: 100.0,
          height: 100.0,
          decoration: BoxDecoration(
            color: Colors.grey,
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            CircularProgressIndicator(),
            Container(height: 10.0,),
            Text('正在加载...',style: TextStyle(fontSize: 16.0,color: Colors.white),)
          ],
        ),
        ),
        )
        : Scaffold(
      body: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: ClassicHeader(
            height: 45.0,
            releaseText: '松开手刷新',
            refreshingText: '刷新中',
            completeText: '刷新完成',
            failedText: '刷新失败',
            idleText: '下拉刷新',
          ),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus mode) {
              Widget body;
              if (mode == LoadStatus.idle) {
                body = Text("已经到底了");
              } else if (mode == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (mode == LoadStatus.failed) {
                body = Text("加载失败！单击“重试”");
              } else {
                body = Text("上拉加载");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: _headerView()),
    );
  }

  @override
  void initState() {
    super.initState();
    message();
  }

  var _res;
  void message() async {
    Response response = await dio.get(
        'http://xssw.gdit.edu.cn/sizheng/api/v1/news?query={"type":"推荐"}&sort=-createdAt');
    _res = response.data;
    setState(() {});
  }



  Widget _headerView() {
    return _res.length==0 
        ? Center(
            child: Image.asset('images/nomessage.png'),
          ):
        CustomScrollView(
            physics: new BouncingScrollPhysics(),
            slivers: <Widget>[
              new SliverAppBar(
                expandedHeight: 200.0,
                pinned: false,
                floating: !true,
                backgroundColor: Colors.grey,
                snap: !true,
                flexibleSpace: new FlexibleSpaceBar(
                    centerTitle: true,
                    background: _res == null
                        ? Center(
                            child: Image.asset('images/nomessage.png'),
                          )
                        : Scaffold(
                            body: Container(
                                width: MediaQuery.of(context).size.width,
                                height: 200.0,
                                child: Swiper(
                                  itemBuilder: _swiperBuilder,
                                  itemCount: 5,
                                  pagination: buildSwiperPagination(),
                                  scrollDirection: Axis.horizontal,
                                  autoplay: true,
                                  onTap: (int index) {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                MessagePage(msg: _res[index])));
                                  },
                                )),
                          )
                    // SwiperPage()
                    ),
              ),
              new SliverList(
                delegate: new SliverChildBuilderDelegate((ctx, index) {
                  if (_res.length < 6) {
                    items.length = 0;
                  } 
                  // else {
                  //   items.length = _res.length - 5;
                  // }
                  return Container(
                      child: ListView.builder(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemCount: items.length,
                    itemBuilder: (context, index) {
                      Widget title;
                      if ('${_res[index + 5]['album']}' != '') {
                        title = Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              width: MediaQuery.of(context).size.width - 150,
                              child: Text(
                                "${_res[index + 5]['title']}",
                                style: TextStyle(fontSize: 16.0),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Container(
                              width: 100,
                              height: 75,
                              margin: EdgeInsets.only(left: 10, top: 5),
                              child: Image.network(
                                '${_res[index + 5]['album']}',
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                        );
                      } else {
                        title = Text(
                          "${_res[index + 5]['title']}",
                          style: TextStyle(fontSize: 16.0),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        );
                      }
                      return Column(
                        children: <Widget>[
                          Container(
                              padding: EdgeInsets.all(0),
                              // width: MediaQuery.of(context).size.width,
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom: BorderSide(
                                          width: 1, color: Color(0xffe5e5e5)))),
                              child: ListTile(
                                title: title,
                                subtitle: Column(
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Container(
                                          child: Text(
                                              "${_res[index + 5]['from']}",
                                              style: TextStyle(fontSize: 13.0)),
                                        ),
                                        Container(
                                          child: Text(
                                              "${_res[index + 5]['createdAt'].substring(0, 10)}",
                                              style: TextStyle(fontSize: 13.0)),
                                          width: 100.0,
                                          height: 25.0,
                                          alignment: Alignment.center,
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                                onTap: () async {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (context) =>
                                          MessagePage(msg: _res[index + 5])));
                                },
                              )),
                        ],
                      );
                    },
                  ));
                }, childCount: 1),
              ),
            ],
          );
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
